package com.vxdata.utils.modules.utils.case_8x;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.vxdata.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName ShortNetAddressUtil
 * @Description 百度生成短链接工具类
 * @Author cutepig
 * @Date 2021/7/17 12:37
 * @Version 1.0
 */
@Slf4j
public class ShortNetAddressUtil {
    final static String CREATE_API = "https://dwz.cn/admin/v2/create";
    // 设置Token，在https://dwz.cn/console/userinfo 获取自己的token，复制粘贴到这里
    final static String TOKEN = "a7ca308c0d3c53357d08e539403c9816";
    //final static String TOKEN = "3ae337784f7d43f19325ad719fca8ff9";

    class UrlResponse {
        @SerializedName("Code")
        private int code;

        @SerializedName("ErrMsg")
        private String errMsg;

        @SerializedName("LongUrl")
        private String longUrl;

        @SerializedName("ShortUrl")
        private String shortUrl;

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getErrMsg() {
            return errMsg;
        }

        public void setErrMsg(String errMsg) {
            this.errMsg = errMsg;
        }

        public String getLongUrl() {
            return longUrl;
        }

        public void setLongUrl(String longUrl) {
            this.longUrl = longUrl;
        }

        public String getShortUrl() {
            return shortUrl;
        }

        public void setShortUrl(String shortUrl) {
            this.shortUrl = shortUrl;
        }
    }

    /**
     * 创建短网址
     *
     * @param longUrl 长网址：即原网址
     * @return 成功：短网址 失败：返回空字符串
     */
    public static String getShortURL(String longUrl) {
        String params = "{\"Url\":\"" + longUrl + "\",\"TermOfValidity\":\"" + "long-term" + "\"}";

        BufferedReader reader = null;
        try {
            // 创建连接
            URL url = new URL(CREATE_API);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.setRequestProperty("Token", TOKEN); // 设置发送数据的格式");

            // 发起请求
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(params);
            out.flush();
            out.close();

            // 读取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            reader.close();

            // 抽取生成短网址
            UrlResponse urlResponse = new Gson().fromJson(res, UrlResponse.class);
            if (urlResponse.getCode() == 0) {
                String shortUrl = urlResponse.getShortUrl();
//                log.debug("longUrl={}, shortUrl={}", longUrl, shortUrl);
                return shortUrl.substring(15);
            } else {
                log.error("获取百度短链接失败 error: {}", urlResponse.getErrMsg());
            }
            return null;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getBaiDuShortURL(String longUrl) {
        int i = 0;
        String shortURL = null;
        do {
            try {
                shortURL = ShortNetAddressUtil.getShortURL(longUrl);
                if (StringUtils.isNotBlank(shortURL)) {
                    return shortURL;
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取百度短链接异常 error, exception = {}", e.getMessage());
            }
            i++;
            if (i > 3) {
                break;
            }
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (Exception e) {
            }
        } while (true);
        return shortURL;
    }


    public static void main(String[] args) {
        String res = getBaiDuShortURL("nkType=1&queryString=''");
        //String res = getShortURL("https://www.baidu.com?linkType=1&queryString=2");
        System.out.println(res);
    }
}